# author: axin
# date: 2021/4/6 20:18
# description:定义任务，文件名只能叫tasks，不能叫其他的
import logging

from django.conf import settings
from django.core.mail import send_mail

from celery_tasks.main import celery_app

# 创建日志输出器
logger = logging.getLogger('django')


@celery_app.task(bind=True, name='send_verify_email', retry_backoff=3)   # 只有在装饰器里写上bind=true  才能在函数参数里写self
def send_verify_email(self, to_email, verify_url):
    """定义发送验证邮件的任务"""
    # send_mail('标题','普通邮件正文','发件人','收件人列表','富文本邮件正文（写html的）')
    subject = "美多商城邮箱验证"
    html_message = '<p>尊敬的用户您好！</p>' \
                   '<p>感谢您使用美多商城。</p>' \
                   '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                   '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
    try:
        send_mail(subject, '', settings.EMAIL_FROM, [to_email], html_message=html_message)
    except Exception as e:
        logger.error(e)
        # 有异常自动重试三次
        raise self.retry(exc=e, max_retries=3)
